package com.chunxuan.langquan.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.CourseCategoryEntity;
import com.chunxuan.langquan.dao.bean.CourseList;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.ui.activity.live.LiveRoomActivity;
import com.chunxuan.langquan.ui.activity.live.PlayBackRoomActivity;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseAdapter;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseViewHolder;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

// 首页
public class Home2Fragment extends BaseFragment {
    //    private Banner banner;
    private static Home2Fragment fragment;
    private TextView tvTitle;
    private TextView tvGoLiveRoom;
    private RecyclerView rlv;
    //    private TextView tvLanguage;
//    private TextView tvEnglish;
//    private TextView tvMath;
//    private TextView tvOther;
//    private TextView tvAll;
    private TextView tvLive;
    private TextView tvPlayBack;
    private View vwLive;
    private View vwPlayBack;
    private LinearLayout llCourseCategory;
    Adapter adapter;

    public Home2Fragment() {

    }

    public static Home2Fragment newInstance() {
        if (fragment == null) {
            fragment = new Home2Fragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_live, container, false);
        tvLive = v.findViewById(R.id.tv_live);
        vwLive = v.findViewById(R.id.vw_live);
        tvPlayBack = v.findViewById(R.id.tv_playback);
        vwPlayBack = v.findViewById(R.id.vw_playback);
        tvTitle = v.findViewById(R.id.tv_title);
        tvGoLiveRoom = v.findViewById(R.id.tv_live_room);
        llCourseCategory = v.findViewById(R.id.ll_course_category);

        rlv = v.findViewById(R.id.rlv);
        rlv.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new Adapter();
        rlv.setAdapter(adapter);
        setListeners();
        requestCourseCategory();
        return v;
    }

    private void setListeners() {
        setOnClickListener(tvLive, tvPlayBack);
    }

    @Override
    public void onClick(View v) {
//        if (v == tvLanguage) {
//            setEnableFalse();
//            tvLanguage.setSelected(true);
//            return;
//        }
//        if (v == tvEnglish) {
//            setEnableFalse();
//            tvEnglish.setSelected(true);
//            return;
//        }
//        if (v == tvMath) {
//            setEnableFalse();
//            tvMath.setSelected(true);
//            return;
//        }
//        if (v == tvOther) {
//            setEnableFalse();
//            tvOther.setSelected(true);
//            return;
//        }
//        if (v == tvAll) {
//            setEnableFalse();
//            tvAll.setSelected(true);
//            return;
//        }
        if (v == tvPlayBack) {
            tvPlayBack.setTextSize(17);
            tvLive.setTextSize(13);
            vwPlayBack.setVisibility(View.VISIBLE);
            vwLive.setVisibility(View.INVISIBLE);
            return;
        }
        if (v == tvLive) {
            tvLive.setTextSize(17);
            tvPlayBack.setTextSize(13);
            vwLive.setVisibility(View.VISIBLE);
            vwPlayBack.setVisibility(View.INVISIBLE);
        }

    }

//    public void setEnableFalse() {
//        tvLanguage.setSelected(false);
//        tvEnglish.setSelected(false);
//        tvMath.setSelected(false);
//        tvOther.setSelected(false);
//        tvAll.setSelected(false);
//    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @SuppressLint("CheckResult")
    public void requestCourseCategory() {
        APIRetrofit.getDefault().requestCourseCategory(Global.HEADER)
                .compose(RxUtil.<BaseResult2<List<CourseCategoryEntity>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<CourseCategoryEntity>>>() {
                    @Override
                    public void accept(BaseResult2<List<CourseCategoryEntity>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            final List<CourseCategoryEntity> categorys = result2.getData();
                            if (!isDataEmpty(categorys)) {
                                llCourseCategory.removeAllViews();
                                for (int i = 0; i < categorys.size(); i++) {
                                    getLayoutInflater().inflate(R.layout.item_live_course_category, llCourseCategory, true);
                                    llCourseCategory.getChildAt(i).setTag(categorys.get(i));
                                    ((TextView) llCourseCategory.getChildAt(i)).setText(categorys.get(i).getLive_category_name());
                                }
                                llCourseCategory.getChildAt(0).setSelected(true);
                                for (int i = 0; i < llCourseCategory.getChildCount(); i++) {
                                    llCourseCategory.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            for (int i1 = 0; i1 < llCourseCategory.getChildCount(); i1++) {
                                                TextView tv = (TextView) llCourseCategory.getChildAt(i1);
                                                tv.setSelected(false);
                                            }
                                            view.setSelected(true);
                                            CourseCategoryEntity entity = (CourseCategoryEntity) view.getTag();
                                            requestCourseList(entity.getLive_category_id());
//                                            requestCourseList(0);
                                        }
                                    });
                                }
                                requestCourseList(categorys.get(0).getLive_category_id());

                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取课程分类失败");
                    }
                });
    }


    @SuppressLint("CheckResult")
    public void requestCourseList(int id) {
        APIRetrofit.getDefault().requestCourseList(Global.HEADER, id)
                .compose(RxUtil.<BaseResult2<CourseList>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<CourseList>>() {
                    @Override
                    public void accept(BaseResult2<CourseList> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            final CourseList categorys = result2.getData();
                            if (!isDataEmpty(categorys.getData())) {
                                List<CourseList.DataBean> lists = new ArrayList<>();
                                String tempData = "";
                                for (int i = 0; i < categorys.getData().size(); i++) {
                                    if (categorys.getData().get(i).getDate().equals(tempData)) {
                                        lists.add(categorys.getData().get(i));
                                    } else {
                                        CourseList.DataBean courseList = new CourseList.DataBean();
                                        courseList.setType(1);
                                        courseList.setDate(categorys.getData().get(i).getDate());
                                        courseList.setWeek(categorys.getData().get(i).getWeek());
                                        lists.add(courseList);
                                        lists.add(categorys.getData().get(i));
                                        tempData = categorys.getData().get(i).getDate();
                                    }
                                }
                                adapter.setDatas(lists);


                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取直播列表失败");
                    }
                });
    }


    static class Adapter extends BaseAdapter<CourseList.DataBean> {

        @NonNull
        @Override
        public BaseViewHolder<CourseList.DataBean> onCreateViewHolder(@NonNull final ViewGroup parent,
                                                                      int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());

            if (viewType == 1) {
                View view = inflater.inflate(R.layout.item_live_head, parent, false);
                ViewHolderHeader viewHolderHeader = new ViewHolderHeader(view);
                viewHolderHeader.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        PushLiveActivity.actionStart(parent.getContext());
                    }
                });
                return new ViewHolderHeader(view);
            } else {
                View view = inflater.inflate(R.layout.item_live_sub, parent, false);
                ViewHolderContent viewHolderContent = new ViewHolderContent(view);
                viewHolderContent.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CourseList.DataBean dataBean = getDatas().get(viewHolderContent.getAdapterPosition());
                        if ("1".equals(dataBean.getStatus())) {
                            LiveRoomActivity.actionStart(parent.getContext(), getDatas().get(viewHolderContent.getAdapterPosition()).getPull_url());
                        } else if ("2".equals(dataBean.getStatus())){
                            ToastUtils.showShort("直播尚未开始");
                        }else{
                            PlayBackRoomActivity.actionStart(parent.getContext(),getDatas().get(viewHolderContent.getAdapterPosition()).getLive_file_url());
                        }
                    }
                });
                return viewHolderContent;
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (getDatas().get(position).getType() != 0) {
                return 1;
            } else {
                return 0;
            }
        }
    }

//       <!--item_live_head-->
//        <!--item_live_sub-->

    static class ViewHolderHeader extends BaseViewHolder<CourseList.DataBean> {
        TextView tvTitle;

        public ViewHolderHeader(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_title);
        }

        @Override
        public void bindViewHolder(CourseList.DataBean value) {
            tvTitle.setText(value.getDate() + "    " + value.getWeek());
        }
    }

    static class ViewHolderContent extends BaseViewHolder<CourseList.DataBean> {
        TextView tvTime;
        TextView tvName;
        TextView tvLiveName;
        ImageView iv;
        TextView tvCategory;
        TextView tvState;

        public ViewHolderContent(@NonNull View itemView) {
            super(itemView);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvName = itemView.findViewById(R.id.tv_name);
            tvLiveName = itemView.findViewById(R.id.tv_live_name);
            iv = itemView.findViewById(R.id.iv_head);
            tvCategory = itemView.findViewById(R.id.tv_category);
            tvState = itemView.findViewById(R.id.tv_state);
        }

        @Override
        public void bindViewHolder(CourseList.DataBean value) {
            tvTime.setText(value.getStart_time() + "-" + value.getEnd_time());
            tvName.setText(value.getTeacher_name());
            tvLiveName.setText(value.getTitle());
            tvCategory.setText(value.getLive_category_name());
            GlideUtil.loadImg(value.getTeacher_avatar(), iv);
            tvState.setText(value.getStatus_text());
        }
    }
}